package cn.fufeiii.bt.common.config;

import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * 跨域配置
 *
 * @author FuFei
 */
@Getter
@Setter
@Configuration
@ConditionalOnProperty(prefix = "cors.config", name = "enabled", havingValue = "true", matchIfMissing = false)
public class CorsConfig {
    @Autowired
    private CorsConfigProperty corsConfigProperty;

    @Bean
    public FilterRegistrationBean<CorsFilter> corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        for (String origin : corsConfigProperty.getAllowedOriginList()) {
            config.addAllowedOrigin(origin);
        }
        for (String origin : corsConfigProperty.getAllowedMethodList()) {
            config.addAllowedMethod(origin);
        }
        for (String origin : corsConfigProperty.getAllowedHeaderList()) {
            config.addAllowedHeader(origin);
        }
        config.setAllowCredentials(true);
        // CORS 配置对所有接口都有效
        source.registerCorsConfiguration(corsConfigProperty.getCorsPathPattern(), config);
        FilterRegistrationBean<CorsFilter> registrationBean = new FilterRegistrationBean<>(new CorsFilter(source));
        registrationBean.setOrder(Ordered.HIGHEST_PRECEDENCE);
        return registrationBean;
    }

}
